﻿namespace StarsAdmin.Core.Extensions;

public static class DateTimeExtension
{
    /// <summary>
    /// 时间戳起始日期
    /// </summary>
    public static readonly DateTime TimestampStart = new(1970, 1, 1, 0, 0, 0, 0);

    /// <summary>
    /// 获取unix时间戳
    /// </summary>
    /// <returns></returns>
    public static int ToUnix(this DateTime date)
    {
        return (int)((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
    }

    /// <summary>
    /// 时间戳转换为日期（时间戳单位秒）
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    public static DateTime UnixToTime(this long timeStamp)
    {
        var start = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        return start.AddMilliseconds(timeStamp).AddHours(8);
    }

    /// <summary>
    /// 时间戳字符串转换为日期（时间戳单位秒）
    /// </summary>
    /// <param name="timeStamp"></param>
    /// <returns></returns>
    public static DateTime UnixToTime(this string timeStamp)
    {
        return Convert.ToInt64(timeStamp).UnixToTime();
    }

    /// <summary>
    /// 转换为时间戳
    /// </summary>
    /// <param name="dateTime"></param>
    /// <param name="milliseconds">是否使用毫秒</param>
    /// <returns></returns>
    public static long ToTimestamp(this DateTime dateTime, bool milliseconds = false)
    {
        var timestamp = dateTime.ToUniversalTime() - TimestampStart;
        return (long)(milliseconds ? timestamp.TotalMilliseconds : timestamp.TotalSeconds);
    }

    /// <summary>
    /// 获取周几
    /// </summary>
    /// <param name="datetime"></param>
    /// <returns></returns>
    public static string GetWeekName(this DateTime datetime)
    {
        var day = (int)datetime.DayOfWeek;
        var week = new string[] { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
        return week[day];
    }
}